﻿PagesScripts.post = {};
PagesScripts.post.isLocked = {};
PagesScripts.post.currentlyReplyingTo = {};

PagesScripts.post.initHandlers = function() {
	if (!HTTPEvents.hasEventListener("onPostLoaded")) {
		HTTPEvents.addEventListener("onPostLoaded", PagesScripts.post.onPostLoaded);
	}

    if (!HTTPEvents.hasEventListener("onPreJumpPageLoaded")) {
		HTTPEvents.addEventListener("onPreJumpPageLoaded", PagesScripts.post.onPreJumpPageLoaded);
	}
	
	if (!HTTPEvents.hasEventListener("onPreCommentPageLoaded")) {
		HTTPEvents.addEventListener("onPreCommentPageLoaded", PagesScripts.post.onPreCommentPageLoaded);
	}

    if (!HTTPEvents.hasEventListener("onPreEditPageLoaded")) {
		HTTPEvents.addEventListener("onPreEditPageLoaded", PagesScripts.post.onPreEditPageLoaded);
	}

    if (!HTTPEvents.hasEventListener("onCommentSent")) {
		HTTPEvents.addEventListener("onCommentSent", PagesScripts.post.onCommentSent);
	}

    if (!HTTPEvents.hasEventListener("onEditPostSent")) {
		HTTPEvents.addEventListener("onEditPostSent", PagesScripts.post.onEditPostSent);
	}

    if (!HTTPEvents.hasEventListener("onJumpSent")) {
		HTTPEvents.addEventListener("onJumpSent", PagesScripts.post.onJumpSent);
	}
    
    $("#postEditTitle").live("keyup", function() {
		PagesScripts.post.setCommentState($("#postEditTitle"), $("#postEditSendButton"));
	});
	
	$("#postCommentTitle").live("keyup", function() {
		PagesScripts.post.setCommentState($("#postCommentTitle"), $("#postCommentSendButton"));
	});
}

PagesScripts.post.loadPost = function() {
	$.mobile.loading('show', {text: 'טוען תגובות באשכול...'});
	$("#postContent", $.mobile.activePage).html("");
	$("#post_name_title", $.mobile.activePage).html(Config.GetCurrentPost().title);
	HTTPManager.GetPost(Config.GetCurrentForum().name, Config.GetCurrentPost().id);
}
 
PagesScripts.post.onPostLoaded = function(event) {
	$.mobile.loading('hide');
	if (event.data && event.data.success != null && event.data.success === true && event.data.post && event.data.post.length > 0) {
		PagesScripts.post.isLocked = event.data.postLocked;
		for (var i=0;i<event.data.post.length;i++) {
			$("#postItem").tmpl(event.data.post[i], {
				isPostLocked:function() {
					return PagesScripts.post.isLocked;
				},
				isMe:function() {
					return Config.getParam("username") != null && Config.getParam("username") != "" && Config.getParam("username").toLowerCase() == this.data.writer.toLowerCase();
				}
			}).appendTo("#postContent", $.mobile.activePage);
		}
		/*
		$("#postItem", $.mobile.activePage).selectmenu("refresh");
		$('#postNew').popup('open', {transition:"pop", positionTo:"window"});
		*/
	}
	else {
		PageManager.changePage('../not_connected_view', {transition: 'pop', role: 'dialog'});  
	}
	
	PagesScripts.post.resizeContent();
	PagesScripts.post.removeObjects();
}

PagesScripts.post.onCommentSent = function(evt) {
    $.mobile.loading('hide');
    // clear form
    $("#postCommentTitle").val("");
    $("#postCommentBody").val("");
    // load post
    PagesScripts.post.loadPost();
}

PagesScripts.post.onEditPostSent = function(evt) {
    PagesScripts.post.loadPost();
}

PagesScripts.post.setJumpPost = function(evt) {
	$.mobile.loading('show', {text: ''});
	HTTPManager.loadPreJumpPage(Config.GetCurrentForum().name, Config.GetCurrentPost().id);
}

PagesScripts.post.setEditPost = function(evt) {
	$.mobile.loading('show', {text: ''});
	PagesScripts.post.currentlyReplyingTo = $.tmplItem(evt.target).data.number;
	HTTPManager.loadPreEditPage(Config.GetCurrentForum().name, Config.GetCurrentPost().id, PagesScripts.post.currentlyReplyingTo);
}

PagesScripts.post.setCommentReplyNumber = function(evt) {
	$.mobile.loading('show', {text: ''});
	PagesScripts.post.currentlyReplyingTo = $.tmplItem(evt.target).data.number;
	HTTPManager.loadPreCommentPage(Config.GetCurrentForum().name, Config.GetCurrentPost().id, PagesScripts.post.currentlyReplyingTo);
}

PagesScripts.post.setCommentState = function(input, button) {
	if (Utils.trim(input.val()) == "") {
		button.addClass("ui-disabled");
	}
	else {
		button.removeClass("ui-disabled")
	}
}

PagesScripts.post.setPostState = function() {
	if (Utils.trim($("#postNewTitle").val()) == "") {
		$("#postNewSendButton").addClass("ui-disabled");
	}
	else {
		$("#postNewSendButton").removeClass("ui-disabled")
	}
}

PagesScripts.post.onPreJumpPageLoaded = function(event) {
	$.mobile.loading('hide');
	if (event.data && event.data.success != null && event.data.success === true) {
		$('#postJump').popup('open', {transition:"pop", positionTo:"window"});
	}
	else {
		PageManager.changePage('../not_connected_jump', {transition: 'pop', role: 'dialog'});
	}
}

PagesScripts.post.onPreCommentPageLoaded = function(event) {
	$.mobile.loading('hide');
	if (event.data && event.data.success != null && event.data.success === true) {
		$("#postEditTitle").val("");
		$("#postEditBody").val("");
		$('#postComment').popup('open', {transition:"pop", positionTo:"window"});
	}
	else {
		PageManager.changePage('../not_connected_comment', {transition: 'pop', role: 'dialog'});  
	}
}

PagesScripts.post.onPreEditPageLoaded = function(event) {
	$.mobile.loading('hide');
	if (event.data && event.data.success != null && event.data.success === true) {
        // Only in edit root, display topic icons
        $("#postEditTitle").val("");
		$("#postEditBody").val("");
		$("#postEditIconContainer > div", $.mobile.activePage).remove();
		
		if (PagesScripts.post.currentlyReplyingTo == 0) {
            var icons = [{}];
            var wheel = [];
            for (var i=0;i<Config.PostIcons.length;i++) {
                wheel.push("<div class='car'><div class='img-cont'><img style='max-height:30px;' src='" + Config.PostIcons[i].icon + "' /></div></div>");
            }
            icons[0]['Icons'] = wheel;
            
            $('#postEditIconType').scroller({
                display: 'inline',
                showLabel:false,
                mode: 'scroller',
                wheels: icons,
                height: 35,
                rows:1,
                onChange:PagesScripts.post.onPostNewIconChanged
            });
			$('#postEditIconType').scroller('setValue', [event.data.postIconId.toString()]);
            $('#postIconsContainer').show();
        } else {
            $('#postIconsContainer').hide();
        }

        $('#postEditTitle').val(Config.Subject);
        $('#postEditBody').val(Config.Body);
		$('#postEdit').popup('open', {transition:"pop", positionTo:"window"});
	}
	else {
		PageManager.changePage('../not_connected_edit', {transition: 'pop', role: 'dialog'});  
	}
}

PagesScripts.post.startNewPost = function() {
	if (!Utils.isAndroid()) {
		PagesScripts.post.setNewPost();
	}
	else {
		PageManager.changePage("../new_post");
	}
}

PagesScripts.post.setNewPost = function() {
	$.mobile.loading('show', {text: ''});
	HTTPManager.loadPrePostPage(Config.GetCurrentForum().name);
}

PagesScripts.post.onPrePostPageLoaded = function(event) {
	$.mobile.loading('hide');
	if (event.data && event.data.success != null && event.data.success === true) {
		$("#postNewTitle").val("");
		$("#postNewBody").val("");
		$("#postNewIconContainer > div", $.mobile.activePage).remove();

		var icons = [{}];
		var wheel = [];
		for (var i=0;i<Config.PostIcons.length;i++) {
			wheel.push("<div class='car'><div class='img-cont'><img style='max-height:30px;' src='" + Config.PostIcons[i].icon + "' /></div></div>");
		}
		icons[0]['Icons'] = wheel;
		
		$('#postNewIconType').scroller({
			display: 'inline',
			showLabel:false,
			mode: 'scroller',
			wheels: icons,
			height: 35,
			rows:1,
			onChange:PagesScripts.post.onPostNewIconChanged
		});
		Config.CurrentSelectedIcon = Config.PostIcons[0].type;
		if (!Utils.isAndroid()) {
			$("#postNew", $.mobile.activePage).popup('open', {transition:"pop", positionTo:"window"});
		}
		else {
			$("#newPostMainContent", $.mobile.activePage).show();
		}
	}
	else {
		PageManager.changePage('../not_connected_post', {transition: 'pop', role: 'dialog'});  
	}
}

PagesScripts.post.onPostNewIconChanged = function(value, inst) {
	Config.CurrentSelectedIcon = Config.PostIcons[value].type;
}

PagesScripts.post.jumpPost = function() {
    // Before Jump a Post, we need to get some details: subject, body, topictype (lame forum system)
    // to get this information, we need to take it from edit page.
	HTTPManager.SendJumpPost(Config.GetCurrentForum().name, Config.GetCurrentPost().id, Config.CurrentSelectedIcon, Config.Subject, Config.Body);
}

PagesScripts.post.sendComment = function() {
    $.mobile.loading('show', {text: 'מפרסם תגובה...'});
	HTTPManager.SendComment(Config.GetCurrentForum().name, Config.GetCurrentPost().id, PagesScripts.post.currentlyReplyingTo, $("#postCommentTitle", $.mobile.activePage).val(), $("#postCommentBody").val());
}

PagesScripts.post.sendEditedPost = function() {
    var currentIcon = Config.CurrentSelectedIcon;
    if (currentIcon == null || isNaN(currentIcon))
        currentIcon = 0;
	HTTPManager.EditPost(Config.GetCurrentForum().name, Config.GetCurrentPost().id, PagesScripts.post.currentlyReplyingTo, currentIcon, $("#postEditTitle", $.mobile.activePage).val(), $("#postEditBody").val());
}

PagesScripts.post.sendPost = function() {
	HTTPManager.SendPost(Config.GetCurrentForum().name, Config.CurrentSelectedIcon, $("#postNewTitle", $.mobile.activePage).val(), $("#postNewBody", $.mobile.activePage).val());
}

PagesScripts.post.onPostSent = function() {
	if (!Utils.isAndroid()) {
		PagesScripts.forumPosts.loadForumPosts(1);
	}
	else {
		PageManager.changePage("../forum_posts");
	}
}

PagesScripts.post.onJumpSent = function() {
    PageManager.changePage("../forum_posts");
}

PagesScripts.post.resizeContent = function() {
	$(".post_content", $.mobile.activePage).each(function() {
		$(this).css("max-width", $(window).width()-20);
	});
	
	$("#postContent img", $.mobile.activePage).each(function() {
		$(this).css("max-width", $(window).width()-40);
	});
}

PagesScripts.post.removeObjects = function() {
	$("#postContent object", $.mobile.activePage).remove();
}